<template>
    <div class="news-carousel">
      <div class="carousel-container"> <!-- 新增容器 -->
        <el-carousel
          ref="carouselRef"
          :interval="4000"
          type="card"
          height="300px"
          class="carousel"
        >
          <el-carousel-item v-for="(item, index) in announcements" :key="item.id">
            <div
              class="carousel-item"
              :style="{ backgroundImage: `url(${item.img})` }"
            >
              <h3>{{ item.title }}</h3>
            </div>
          </el-carousel-item>
        </el-carousel>
  
        <div class="title-bar">
          <h3
            v-for="(item, index) in announcements"
            :key="item.id"
            @mouseenter="jumpToSlide(index)" 
            class="title-item"
          >
            {{ item.title }}
          </h3>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { noticeListService } from '@/api/announcement.js';
  
  const announcements = ref([]);
  const carouselRef = ref(null); // 引用 carousel 组件
  
  const fetchAnnouncements = async () => {
    try {
      const response = await noticeListService();
      announcements.value = response.data.slice(0, 5); // 提取前五个公告
      console.log('公告列表:', announcements.value); // Console 输出公告列表
    } catch (error) {
      console.error('获取公告失败:', error);
    }
  };
  
  const jumpToSlide = (index) => {
    if (carouselRef.value) {
      carouselRef.value.activeIndex = index; // 切换轮播器到对应的项
    }
  };
  
  onMounted(() => {
    fetchAnnouncements();
  });
  </script>
  
  <style scoped>
  .news-carousel {
    display: flex;
    flex-direction: column;
    height: 500px; /* 提高容器高度以适应轮播项 */
  }
  
  .carousel-container {
    display: flex; /* 使用 Flexbox 布局 */
    flex: 1;
  }
  
  .carousel {
    flex: 1; /* 轮播器自适应高度 */
    position: relative;
  }
  
  .carousel-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px; /* 提高轮播项高度 */
    background-color: red; /* 默认背景色 */
    background-size: cover; /* 背景图像覆盖 */
    background-position: center;
    color: white; /* 字体颜色 */
    text-align: center;
  }
  
  .title-bar {
    display: flex;
    flex-direction: column; /* 垂直排列标题 */
    width: 200px; /* 设置标题区域宽度 */
    padding: 10px;
  }
  
  .title-item {
    margin: 5px 0;
    color: #333; /* 标题颜色 */
    cursor: pointer; /* 鼠标悬浮手型样式 */
    transition: background-color 0.3s; /* 添加过渡效果 */
  }
  
  .title-item:hover {
    background-color: #f0f0f0; /* 悬浮时的背景色 */
  }
  </style>
  